import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useLocation, useNavigate } from 'react-router-dom';
import { NavBar, Space, Toast,ActionSheet, Button, Dialog } from 'antd-mobile';
import { CloseOutline, MoreOutline, SearchOutline } from 'antd-mobile-icons';
import tx from './6.jpg'
import style from  '../lyf/Detail.module.css'

export default function Detail() {
  const navigate = useNavigate();
  const location = useLocation();
  // 尝试从本地存储获取id，如果没有则从url获取
  const storedId = localStorage.getItem('itemid');
  const urlId = location.search.split('=')[1];
  const id = storedId || urlId;
  const [detailq, setDetailq] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [visible, setVisible] = useState(false);
  const [argeen,setargeen]=useState('')

  const actions = [
      { text: '同意', key: 'yes' },
      { text: '不同意', key: 'no' },
  ];

  // 处理ActionSheet点击事件
  const handleAction = (action) => {
    let newStatus;
    if (action.key === 'yes') {
      // 同意 - 状态变为已通过(3)
      newStatus = '3';
      Toast.show({
        icon: 'success',
        content: '已同意申请',
      });
    } else if (action.key === 'no') {
      // 不同意 - 状态变为已拒绝(4)
      newStatus = '4';
      Toast.show({
        icon: 'fail',
        content: '已拒绝申请',
      });
    }

    // 更新状态
    if (newStatus) {
      axios.put(`http://localhost:3111/qingjia/update_status/${id}`, { zhuangtai: newStatus })
        .then(res => {
          if (res.data.code === 200) {
            console.log(`请假申请状态已更新为${newStatus === '3' ? '已通过' : '已拒绝'}`);
            // 关闭ActionSheet
            setVisible(false);
            // 返回列表页
            setTimeout(() => {
              navigate('/zhu/xiaoxi');
            }, 1500);
          }
        })
        .catch(err => {
          console.error('更新状态失败:', err);
          Toast.show({
            icon: 'fail',
            content: '操作失败',
          });
        });
    }
  };

  const back = () => {
    navigate('/zhu/xiaoxi')
  };

  const getqing = () => {
    if (!id) {
      setError('ID参数无效');
      setLoading(false);
      return;
    }

    // 使用新的API直接根据ID获取详情
    axios.get(`http://localhost:3111/qingjia/detail/${id}`)
      .then(res => {
        if (res.data.code === 200) {
          setDetailq(res.data.data);
        } else {
          setError('获取数据失败');
        }
      })
      .catch(err => {
        console.error('获取请假详情失败:', err);
        setError('获取数据失败');
      })
      .finally(() => {
        setLoading(false);
      });
  };
  useEffect(() => {
    getqing();
  }, [id]);

  useEffect(() => {
    // 如果从url获取到id，将其存入本地存储
    if (urlId) {
      localStorage.setItem('detailItemId', urlId);
    }
  }, [urlId]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return <div className="error">{error}</div>;
  }

  if (!detailq) {
    return <div>未找到对应数据</div>;
  }

  return (
    <div>
      <NavBar onBack={back}>请假详情</NavBar>
      <p style={{ fontSize: '15px', marginLeft: '10px', color: 'rgb(61,158,109)' }}>申报人信息</p>
      <div className={style.xinxi}>
        <div style={{ display: 'flex' }}>
          <img src={tx} className={style.toux} />
          <p style={{ fontSize: '25px', marginTop: '50px', marginLeft: '10px' }}>{detailq.username}</p>
        </div>
        <div style={{ marginLeft: '20px' }}>
          <p className={style.jingli}>{detailq.zhiye}<br />Managere</p>
          <p style={{ fontSize: '18px', marginTop: '15px', marginLeft: '10px' }}>所属部门：{detailq.bumen}</p>
        </div>
      </div>
      <p style={{ fontSize: '15px', marginLeft: '10px', color: 'rgb(61,158,109)', marginTop: '20px' }}>请假详情</p>
      <hr style={{ marginTop: '10px' }} />
      <p style={{ fontSize: '16px', marginLeft: '20px', color: 'rgb(180,180,180)', marginTop: '10px' }}>申请时间：2025-5-10</p>
      <ul className={style.detail}>
        <li>请假类型：{detailq.QJtype}</li>
        <li>调休日期：{detailq.KStime}</li>
        <li>请假方式：{detailq.QJfangshin}</li>
        <li>开始时间：{detailq.KStime} 00:00:00</li>
        <li>结束时间：{detailq.JStime} 00:00:00</li>
        <li>请假原因：{detailq.yuanyin}</li>
      </ul>
      <div className={style.liucheng}>
        <div style={{display:'flex'}}>
          <img src={tx} />
          <div style={{marginLeft:'10px',marginTop:'50px'}}>
            <span style={{fontSize:'18px',color:'rgb(51,102,204)',fontWeight:'bolder'}}>同意</span>自动审批<br />
            直接上级审批 雷静 2025-05-11 18:20:36
          </div>
          
        </div>
        <div style={{display:'flex'}}>
          <img src={tx} />
          <div style={{marginLeft:'10px',marginTop:'50px'}}>
          <span style={{fontSize:'18px',color:'rgb(51,102,204)',fontWeight:'bolder'}}>等待审批</span><br />
            等待行政专员审批流程
            </div>
        </div>
        <div style={{display:'flex'}}>
          <p className={style.no}>?</p>
          <div style={{marginLeft:'10px',marginTop:'60px',fontSize:'17px',color: 'rgb(180,180,183)'}}>
            完成
          </div>
        </div>
      </div>
      <div className={style.liu}></div>
      <div className={style.liu2}></div>
      <p style={{ fontSize: '15px', marginLeft: '10px', color: 'rgb(61,158,109)' }}>审批意见</p>
      <hr style={{ marginTop: '10px' }} />
      <ul className={style.argee}>
        <li>
          意见内容：<input type='radio' value={argeen} onChange={(e)=>setargeen(e.target.value)} checked />同意
          <input type='radio' value={argeen} onChange={(e)=>setargeen(e.target.value)} />不同意
        </li>
        <li>
          意见内容：<input type='text' style={{border:'1px solid grey',height:'30px'}} placeholder='陈述内容...' />
        </li>
      </ul>
      <div style={{marginLeft:'30px',marginTop:'90px'}}>
        <button className={style.btn}>附件上传</button>
        <button className={style.btn} onClick={() => setVisible(true)}>提交</button>
        <ActionSheet 
          cancelText='取消' 
          visible={visible} 
          actions={actions} 
          onAction={handleAction}
          onClose={() => setVisible(false)}
        />
      </div>
      
    </div>
  );
}